import React, { useEffect, useState, useRef } from 'react';
import { useDispatch, connect } from 'umi';
import {
  Button,
  Card,
  Col,
  Collapse,
  ConfigProvider,
  Empty,
  Form,
  Row,
  Select,
  Table,
  Input,
} from 'antd';
import type { ColumnsType, SorterResult, TableProps } from 'antd/es/table';
import { ProForm, ProFormText, ProFormSelect } from '@ant-design/pro-form';
import zhCN from 'antd/lib/locale/zh_CN';
import { FormInstance } from 'antd/lib/form';

const { Panel } = Collapse;

const SchoolPrecaution = (props: any) => {
  // console.log( JSON.parse(props.user.currrentuser))
  const onClick = (record: any) => {
    props.add({
      key: '2',
      name: record.studentName,
      stuNumber: record.studentCode,
    });
  };
  // 表格列标题
  const columns: ColumnsType<any> = [
    {
      title: '预警级别',
      dataIndex: 'alertLevel',
      sorter: (a, b) => a.alertLevel - b.alertLevel,
      width: '10%',
    },
    {
      title: '挂科数',
      dataIndex: 'failedSubjectsCount',
      sorter: (a, b) => a.failedSubjectsCount - b.failedSubjectsCount,
      width: '10%',
    },
    {
      title: '姓名',
      dataIndex: 'studentName',
      width: '10%',
      render: (_, record: any) => (
        <a
          onClick={() => {
            onClick(record);
          }}
        >
          {record.studentName}
        </a>
      ),
    },
    {
      title: '学号',
      dataIndex: 'studentCode',
      width: '15%',
    },
    {
      title: '班级',
      dataIndex: 'classLabel',
      width: '15%',
    },
    {
      title: '年级',
      dataIndex: 'year',
      width: '15%',
    },
    {
      title: '专业',
      dataIndex: 'majorLabel',
      width: '15%',
    },
    {
      title: '班导师',
      dataIndex: 'mentorName',
      width: '10%',
    },
  ];
  const dispatch = useDispatch();
  const formRef = useRef<FormInstance>();
  const [result, setResult] = useState([]);
  const [initialData, setInitialData] = useState<Array<any>>([]); // 保存初始数据

  useEffect(() => {
    dispatch({
      type: 'Model_StudentAnalysisStudentModel/getSchoolPrecautionEffects',
      payload: {
        teacherCode: JSON.parse(props.user.currrentuser).account,
        callback: (value: any) => {
          console.log(value);
          setResult(value);
          setInitialData(value); // 保存初始数据
        },
      },
    });
  }, []);

  const handleChange: TableProps<any>['onChange'] = (
    pagination,
    filters,
    sorter,
  ) => {};

  //筛选
  const searchOnFinish = async (values: any) => {
    // 获取表单值
    let alertLevel = values.alertLevel;
    let failedSubjectsCount = values.failedSubjectsCount;
    let studentName = values.studentName;
    let classLabel = values.classLabel;
    let year = values.year;
    let majorLabel = values.majorLabel;
    let mentorName = values.mentorName;

    // 过滤逻辑
    let filteredData = result.filter((item: any) => {
      if (item.alertLevel !== alertLevel) {
        return false;
      }
      if (
        failedSubjectsCount &&
        !item.failedSubjectsCount.includes(failedSubjectsCount)
      ) {
        return false;
      }
      if (
        studentName &&
        item.studentName &&
        !item.studentName.includes(studentName)
      ) {
        return false;
      }
      if (
        classLabel &&
        item.classLabel &&
        !item.classLabel.includes(classLabel)
      ) {
        return false;
      }
      if (year && !item.year.toString().includes(year)) {
        //year是number类型，需要转为字符串
        return false;
      }
      if (
        majorLabel &&
        item.majorLabel &&
        !item.majorLabel.includes(majorLabel)
      ) {
        return false;
      }
      if (
        mentorName &&
        item.mentorName &&
        !item.mentorName.includes(mentorName)
      ) {
        //mentor可能为空，需要提前判断
        return false;
      }
      return true;
    });

    // 更新结果
    setResult(filteredData);
  };

  //重置
  const handleReset = () => {
    formRef.current?.resetFields();
    setResult(initialData); // 重置为初始数据
  };

  return (
    <ConfigProvider locale={zhCN}>
      {/* 搜索区 */}
      <Card
        title={
          <span style={{ fontWeight: 'bold', fontSize: 18 }}>全部预警列表</span>
        }
      >
        <ProForm
          layout="inline"
          onFinish={searchOnFinish}
          onReset={handleReset}
        >
          <ProFormSelect
            label="预警级别"
            name="alertLevel"
            initialValue=""
            width={160}
            options={[
              { value: 1, label: '一级预警' },
              { value: 2, label: '二级预警' },
              { value: 3, label: '三级预警' },
            ]}
          />
          <ProFormText
            label="挂科数"
            name="failedSubjectsCount"
            placeholder="请输入挂科数"
            width={160}
          />
          <ProFormText
            label="姓名"
            name="studentName"
            placeholder="请输入学生姓名"
            width={160}
          />
          <ProFormText
            label="班级"
            name="classLabel"
            placeholder="请输入班级"
            width={160}
          />
          <ProFormText
            label="年级"
            name="year"
            placeholder="请输入年级"
            width={160}
          />
          <ProFormText
            label="专业"
            name="majorLabel"
            placeholder="请输入专业"
            width={200}
          />
          <ProFormText
            label="班导师"
            name="mentorName"
            placeholder="请输入导师姓名"
            width={160}
          />
        </ProForm>
      </Card>
      {/* 信息展示区 */}
      <Card>
        <Table columns={columns} dataSource={result} onChange={handleChange} />
      </Card>
    </ConfigProvider>
  );
};

export default connect(({ Model_StudentAnalysisStudentModel, user }: any) => ({
  Model_StudentAnalysisStudentModel,
  user,
}))(SchoolPrecaution);
